package cn.chendd.core;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.List;
import java.util.Map;

/**
 * 合并文件
 * @author chendd
 *
 */
public class MergeFile {

    /**
     * 合并文件
     * @param propFile 分割文件的属性文件路径
     */
    public static void mergeFile(String propFile) throws IOException,
            FileNotFoundException, ClassNotFoundException {
        File file = new File(propFile);
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
        Object obj = ois.readObject();
        if(obj instanceof Map == false){
            System.out.println("文件以及损坏");
        }
        @SuppressWarnings("unchecked")
        Map<String , Object> propMap = (Map<String, Object>) obj;
        String fileName = (String) propMap.get("fileName");//源文件名称
        /**文件大小,科学一点的判定可以判定当前磁盘可用存储空间是否可以容纳本次还原文件**/
        //碎片文件
        @SuppressWarnings("unchecked")
        List<String> partList = (List<String>) propMap.get("partList");
        File srcFile = new File(file.getParent() + File.separator + fileName);
        if(srcFile.exists()){
            srcFile.delete();
        }
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(srcFile, true));
        byte b[] = new byte[1024];
        for (String partName : partList) {
            String filePath = file.getParent() + File.separator + partName;
            //循环读取文件
            InputStream is = new FileInputStream(filePath);
            int lens = 0;
            while((lens = is.read(b)) != -1){
                bos.write(b , 0 , lens);
            }
            is.close();
        }
        bos.flush();
        bos.close();
    }

}
